<?php
namespace control;
// 人员动态报表
class personnelDynamicsClass extends adIndexClass
{
    private const page = 'personnelDynamics';
    private array $list = ['board' => '数据看板', 'entry_quit_trend' => '入职、离职趋势', 'dep_distribute' => '入职、离职人员部门分布', 'turnover_rate' => '离职率趋势', 'recruitment_channels' => '招聘渠道','quit_reason' => '离职原因'];

    /*返回网页*/
    public function home()
    {
        $root = root;
        // 搜索文本框
        $searchTxt =
            "<form name='mainForm'>" .
            selectMultiple(["name" => "departmentId", 'table' => " department", 'class' => " text width200", 'sqlId' => 'id', 'sqlField' => 'name', 'title' => '部门']).
            text([
                'name'    => 'date',
                'title'   => "时间段",
                "class"   => "text text-data width200",
                "value"   => date('Y-m') . '-01 ~ ' . date('Y-m-d'),
                'laydate' => ['range' => '~', 'type' => 'date',],
            ]) .
            "<input class='searchSub' type='button' onclick='cardSearch()' value='查询'></form>";

        //$record = query('user_setting',"stid = '".self::$stid."' and type = '人员动态'");
        $setting = ["board", "entry_quit_trend", "dep_distribute", "turnover_rate", "recruitment_channels", "quit_reason"];
        $board = in_array('board', $setting) ? 'display:block;' : 'display:none;';
        $entry_quit_trend = in_array('entry_quit_trend', $setting) ? 'display:block;' : 'display:none;';
        $dep_distribute = in_array('dep_distribute', $setting) ? 'display:block;' : 'display:none;';
        $turnover_rate = in_array('turnover_rate', $setting) ? 'display:block;' : 'display:none;';
        $recruitment_channels = in_array('recruitment_channels', $setting) ? 'display:block;' : 'display:none;';
        $quit_reason = in_array('quit_reason', $setting) ? 'display:block;' : 'display:none;';

        $html = <<<EOT
        <style>
            .title-card-li-content{
              text-align: center;padding-top: 50px
            }
            .title-card-li-money{
              font-size: 28px;font-weight: bold
            }
            .spread-box{
                float: left;
                margin: 5px 0 -5px 0;
                width: 98.5%;
            }
            .time_switching{
                display: inline-block;
                width: 80px;
                height: 26px;
                line-height: 26px;
                background-color: #e6e6e6;
                text-align: center;
                margin-right: 15px;
                cursor: pointer;
            }
            .text-data{
                margin-right: 15px;
            }
            .quarter {
                width: 19%;
            }
        </style>
        <!--<div class="chart_setting"><img onclick="layer('salesReportForm','setting',{})" src="{$root}img/control/menu_two.svg" alt=""></div>-->
        <div class="home-warp">
            <div class="spread-box">
                <div class="data-widget search">$searchTxt</div>
            </div>
            <div class="left-box">
                <div class="data-widget" style="{$board}">
                    <span class="title-card">数据看板</span>
                    <ul class="revenue" id="hrDataHtml">
                        <li class="quarter left vertical-line-hr">
                            <div class="hr-div">
                                <p class="hr-p gray f-14">入职人数</p>
                                <p class="hr-p f-30">0</p>
                            </div>
                        </li>
                        <li class="quarter left vertical-line-hr">
                            <div class="hr-div">
                                <p class="hr-p gray f-14">离职人数</p>
                                <p class="hr-p f-30">0</p>
                            </div>
                        </li>
                        <li class="quarter left vertical-line-hr">
                            <div class="hr-div">
                                <p class="hr-p gray f-14">在职人数</p>
                                <p class="hr-p f-30">0</p>
                            </div>
                        </li>
                        <li class="quarter left vertical-line-hr">
                            <div class="hr-div">
                                <p class="hr-p gray f-14">离职率</p>
                                <p class="hr-p f-30">0%</p>
                            </div>
                        </li>
                    </ul>
                </div>
                <div class="half left data-widget" style="width: 97.5%;{$entry_quit_trend}">
                    <p><span class="title-card">入职、离职趋势</span></p>
                   <div class="data-box-show" id="entryQuitTrendHtml"></div>
                </div>
                <div class="half left data-widget" style="{$dep_distribute}">
                    <p><span class=\"title-card\">入职、离职人员部门分布</span></p>
                    <div class="data-box-show" id="depDistributeHtml"></div>
                </div>
                <div class="half left data-widget" style="{$turnover_rate}">
                    <p><span class=\"title-card\">离职率趋势</span></p>
                    <div class="data-box-show" id="turnoverRateHtml"></div>
                </div>
            </div>
            <div class="right-box">
              <div class="data-widget" style="{$recruitment_channels}">
                   <p><span class="title-card">招聘渠道</span></p>
                   <div class="data-box-show" id="recruitmentChannelsHtml"></div>
                </div>
                <div class="data-widget" style="{$quit_reason}">
                   <p><span class="title-card">离职原因</span></p>
                   <div class="data-box-show" id="quitReasonHtml"></div>
                </div>
            </div>
        </div>
    </div>
     <script src='{$this->root}static/javascript/echarts.min.js'></script>
<script>
function search_line(form,cla,fun) {
     $("#" + fun + "Html").html("数据查询中，请稍后。。。");
     //串联表单
        var formName = form.split(",");
        var serialize = "";
        var a = "";
        for (var i = 0; i < formName.length; i++) {
            if (serialize == "") {
                a = "";
            } else {
                a = "&";
            }
            if (formName[i] != "") {
                serialize += a + $("[name=" + formName[i] + "]").serialize();
            }
        }
    $.post(root + "control/adIndex.html?cla=" + cla + "&fun=" + fun, serialize, function (data) {
         $("#" + fun + "Html").html(data.html);
    }, "json");
}

/**
* 看板搜索
*/
function cardSearch(){
    ['hrData', 'entryQuitTrend', 'depDistribute', 'turnoverRate'].forEach((fun)=>{
                    search_line('mainForm','homepage', fun)
    });
    ['recruitmentChannels', 'quitReason'].forEach((fun)=>{
                    search_line('mainForm','personnelDynamics', fun)
    });
}

$(function() {
    ['hrData', 'entryQuitTrend', 'depDistribute', 'turnoverRate'].forEach((fun)=>{
                    search_line('mainForm','homepage', fun)
    });
    ['recruitmentChannels', 'quitReason'].forEach((fun)=>{
                    search_line('mainForm','personnelDynamics', fun)
    })
})


</script>
EOT;
        $style = '<style>#body{background-color:#f2f2f2;padding:0 10px}.right-box-ul{
            height: 500px;
            max-height: none;
         }
         .right-box-title{
            display: flex;
         }
         .right-text{
            height: auto;
         }
         .right-box-title li{
            float: left;margin: 5px 10px;min-width: 70px;text-align: center;
         }
         .data-widget-select{
            margin-right: 10px;
         }
         .data-widget-select .fs-label{
             height: 15px;line-height: 15px;
         }
         .data-widget-select .fs-label-wrap{
             border-radius: 4px;
         }
         .aim-rank li{
            margin: 5px 0;
         }
         .aim-rank .right-box-title li:nth-child(1){min-width: 40px}
         .aim-rank .right-box-title li:nth-child(2){min-width: 50px}
         .aim-rank .right-box-title li:nth-child(3){min-width: 100px}
         .aim-rank .right-box-title li:nth-child(4){min-width: 100px}
</style>';
        return head("ad") . $style . $this->adheader(["主页"]) . $html . warn() . $this->adfooter();
    }

    /**
     * 显示设置
     * @return bool|string
     */
    public function setting()
    {
        $list = $this->list;
        $li = '';
        $index = 0;
        $setting = query('user_setting', "type='人员动态' and stid = '" . self::$stid . "'");
        $setText = (array)json_decode($setting['value'], true);
        foreach ($list as $id => $name) {
            $index++;
            $checked = '';
            if (in_array($id, $setText)) {
                $checked = 'checked';
            }
            $li .= <<<eof
 <li><div class="li-content"><span class="left">{$name}</span><div class="switch">
                  <input id="cmn-toggle-{$index}" name='setting[]' value='{$id}' $checked class="cmn-toggle cmn-toggle-round" type="checkbox">
                  <label for="cmn-toggle-{$index}"></label>
            </div></div></li>
eof;
        }
        //生成表单
        $html = <<<efo
<form name="settingForm">
<div class="setting-content">
    <ul>
       {$li}
    </ul>
   
</div>
<div style="width: 100%;text-align: center"><button class="button" onclick="subForm('settingForm',root+'control/adIndex.html?cla=salesReportForm&fun=settingEdit')">保存</button></div>
</form>
<style>
.li-content{height: 30px;line-height: 30px}
.setting-content>ul{margin: 25px}
.setting-content>ul>li{width: 100%;border-bottom: 1px solid #F2F2F2;padding: 8px 0;}
.switch{display: inline-block;vertical-align: bottom;float: right}
</style>
efo;

        //返回弹出层
        return $this->layer(array("title" => '设置图表展示', "height" => 550, "width" => 400, "html" => $html));
    }

    /**
     * 图标展示设置
     * @return bool|string
     */
    public function settingEdit(): bool|string
    {
        $setting = $this->post('setting') ?: [];
        $record = query('user_setting', "type='人员动态' and stid = '" . self::$stid . "'");
        if (!empty($record['id'])) {
            $json['warn'] = static::update(array(
                'table' => 'user_setting',
                'field' => [
                    'value' => json_encode($setting, 320)
                ],
                'where' => "id = '$record[id]'"
            ));
        } else {
            $json['warn'] = static::insert(array(
                'table' => 'user_setting',
                'field' => [
                    'stid' => self::$stid,
                    'type' => '人员动态',
                    'value' => json_encode($setting, 320)
                ],
            ));
        }
        if (in_array($json['warn'], ['新增成功', '更新成功'])) {
            $json['warn'] = 2;
        }
        return json_encode($json, 320);
    }

    /**
     * 招聘渠道 - 返回数据
     */
    public function recruitmentChannels(): bool|string
    {
        $inventoryReportForm = new inventoryReportFormClass();
        $date = $this->post('date');
        if (!empty($date)) {
            $timeArr = explode(' ~ ', $date);
        } else {
            $timeArr[0] = date('Y-m') . '-01';
            $timeArr[1] = $this->date;
        }
        $departmentId = $this->post('departmentId');
        $and     = '';
        if ($departmentId) {
            $departments = homepageClass::getDepartmentSub(["where" => " pid = '$departmentId' "]);
            $departments = array_merge([$departmentId], explode(',', trim($departments)));
            $and         .= "  and jobId in (select id from job where departmentId in ('" . implode("','", $departments) . "')) ";
        }
        $talentSourceOption = explode('，', para('talentSourceOption'));
        $series = [];
        foreach ($talentSourceOption as $val) {
            $entryNum = find([
                    'table'  => "staff_entry_record",
                    'field'  => "IFNULL(count(id),0) as num",
                    'single' => " state = '已通过' and entryDate between '$timeArr[0]' and '$timeArr[1]' " . $and,
                ])['num'] ?? 0;
            $series[] = ['name' => $val, 'data' => $entryNum];
        }
        $data         = [
            "text" => '',
            "subtext" => '',
            "series" => $series,
        ];
        $json['html'] = "<div style='height: 100%'>".$inventoryReportForm->pie($data)."</div>";
        return json_encode($json, 320);
    }
    /**
     * 离职原因 - 返回数据
     */
    public function quitReason(): bool|string
    {
        $inventoryReportForm = new inventoryReportFormClass();
        $date = $this->post('date');
        if (!empty($date)) {
            $timeArr = explode(' ~ ', $date);
        } else {
            $timeArr[0] = date('Y-m') . '-01';
            $timeArr[1] = $this->date;
        }
        $departmentId = $this->post('departmentId');
        $and     = '';
        if ($departmentId) {
            $departments = homepageClass::getDepartmentSub(["where" => " pid = '$departmentId' "]);
            $departments = array_merge([$departmentId], explode(',', trim($departments)));
            $and         .= "  and jobId in (select id from job where departmentId in ('" . implode("','", $departments) . "')) ";
        }
        $reasonOption = explode('，', para('reasonOption'));
        $series = [];
        foreach ($reasonOption as $val) {
            $quitNum = find([
                    'table'  => "staff_quit_record",
                    'field'  => "IFNULL(count(id),0) as num",
                    'single' => " state = '已通过' and confirmDate between '$timeArr[0]' and '$timeArr[1]' " . $and,
                ])['num'] ?? 0;
            $series[] = ['name' => $val, 'data' => $quitNum];
        }
        $data         = [
            "text" => '',
            "subtext" => '',
            "series" => $series,
        ];
        $json['html'] = "<div style='height: 100%'>".$inventoryReportForm->pie($data)."</div>";
        return json_encode($json, 320);
    }
}
